import React from "react";
import { Toast, Carousel, Grid, Modal } from "antd-mobile";
import wx from "weixin-js-sdk";

const prompt = Modal.prompt;

export default class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      menu: [
        // 	{
        // 	icon: require('../../imgs/icon1.png'),
        // 	name: '商业',
        // 	path: '/page/home/home/classify/2',
        // },{
        // 	icon: require('../../imgs/icon2.png'),
        // 	name: '职业',
        // 	path: '/page/home/home/classify/3',
        // },{
        // 	icon: require('../../imgs/icon3.png'),
        // 	name: '抖音',
        // 	path: '',
        // },{
        // 	icon: require('../../imgs/icon4.png'),
        // 	name: '兑换专区',
        // 	path: '/page/home/home/classify/1',
        // },{
        // 	icon: require('../../imgs/icon5.png'),
        // 	name: '全部分类',
        // 	path: '/page/home/home/classify/-1',
        // },
        {
          icon: require("../../imgs/icon6.png"),
          name: "交流活动",
          path: "/page/home/home/activity/抖音培训/1",
        },
        {
          icon: require("../../imgs/icon7.png"),
          name: "艺看直播",
          path: "https://appk5t7cihk5766.h5.xiaoeknow.com/homepage",
          //path: "/page/home/home/service/租借服务/2",
        },
        {
          icon: require("../../imgs/icon8.png"),
          name: "活动报名",
          path: "/page/home/home/activity/活动报名/2",
        },
        {
          icon: require("../../imgs/icon9.png"),
          name: "公益活动",
          path: "/page/home/home/activity/公益活动/3",
        },
        {
          icon: require("../../imgs/icon10.png"),
          name: "创作服务",
          path: "/page/home/home/service/创作服务/1",
        },
      ],
      banner: [],
      category: [],
      server_casee: [],
      hot_goods: [], //主编力荐
      active: [], //交流活动
      hot_active: [], //火热报名中
      data: [],
      img: [],
      live_status: 0,
      live_time: 0,
      live_money: "",
      new_time: 0,
    };
  }
  componentDidMount() {
    document.title = "发现";
    this.getData();
    global.Ajax.hhtc_request("user/get_qrcode", {}).then((data) => {
      console.log("第一步 ", data);
      if (data.code === 1) {
        this.setState(data.data);
      }
    });

    global.Ajax.hhtc_request("web/get_share", {
      windowurl: window.location.href,
    }).then((data) => {
      console.log("分享页面的数据 ", data);
      if (data.code === 1) {
        wx.config({
          debug: false,
          appId: data.data.appId,
          timestamp: data.data.timestamp,
          nonceStr: data.data.noncestr,
          signature: data.data.signature,
          jsApiList: [
            // 所有要调用的 API 都要加到这个列表中
            "updateTimelineShareData", //分享给好友
            "updateAppMessageShareData", //分享到朋友圈
          ],
        });

        wx.checkJsApi({
          jsApiList: ["updateTimelineShareData", "updateAppMessageShareData"], // 需要检测的JS接口列表，所有JS接口列表见附录2,
          success: function (res) {
            console.log("checkJsApi--", res);
            // 以键值对的形式返回，可用的api值true，不可用为false
            // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
          },
        });
        wx.error(function (res) {
          console.log(res);
          // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        });

        wx.ready(() => {
          //配置好需要分享的几个配置，这里只是演示，实际开发中应该是动态的变量
          var shareData = {
            title: "好友邀请你加入艺看学院",
            desc: "你的好友正在邀请你加入艺看学院，快来看看吧",
            link: window.location.href.split("#")[0],
            imgUrl:
              "https://yksy.qianjitianxia.com/o_1eiao12gcfa6122j1eicun0pjl8.png", //传递给微信需传递完整的带url链接
            success: function () {
              global.Ajax.hhtc_request("user/share", {}).then((data) => {
                console.log("data: ", data);
                // return Toast.success(data.msg);
              });
            },
          };

          //调用各个接口并传入配置变量
          wx.updateTimelineShareData(shareData);
          wx.updateAppMessageShareData(shareData);
        });
      }
    });

    let uid = localStorage.getItem("uid");
    let openid = localStorage.getItem("openid");

    var code = this.GetQueryValue("code");

    var local = window.location.href;

    if (uid && !openid) {
      if (code) {
        global.Ajax.hhtc_request("index/index", { code: code, uid: uid }).then(
          (data) => {
            if (data.code == 1) {
              localStorage.setItem("openid", data.data);
              window.location.href = "https://yikan.duoduoduo.work";
            } else {
              window.location.href = data.data;
            }
          }
        );
      } else {
        window.location.href =
          "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx54a099859f2845a9&redirect_uri=" +
          encodeURIComponent(local) +
          "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
      }
    }
  }

  getData() {
    Toast.loading();
    global.Ajax.hhtc_request("home/home", {}).then((data) => {
      console.log("全部数据 ", data);
      Toast.hide();
      if (data.code === 1) {
        var category = data.data.category;
        category.push({
          icon: require("../../imgs/icon5.png"),
          title: "全部分类",
          id: -1,
        });

        //console.log('data.data.hot_goods: ', data.data.hot_goods);
        this.setState({
          banner: data.data.banner,
          category: category,
          server_casee: data.data.server_casee,
          hot_goods: data.data.hot_goods,
          active: data.data.active,
          hot_active: data.data.hot_active,
          data: data.data.data,
          img: data.data.img,
          live_status: data.data.live_status,
          live_time: data.data.live_time,
          live_money: data.data.live_money,
        });
        console.log("this.state.live_status: ", this.state.live_status);
        console.log("this.state.live_time: ", this.state.live_time);
        console.log("this.state.live_money: ", this.state.live_money);
      }
    });
  }

  GetQueryValue(queryName) {
    var query = decodeURI(window.location.search.substring(1));
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split("=");
      if (pair[0] == queryName) {
        return pair[1];
      }
    }
    return null;
  }
  // bander  点击支付5朵小红花
  xh() {
    if (this.state.live_status === 0) {
      prompt(
        <p>
          <img
            alt=''
            src={require("../../imgs/hua.png")}
            style={{ display: "block", width: "9.334vw", margin: "0 auto" }}
          />
          <b style={{ display: "block", margin: "10px 0 0 0" }}>
            观看直播需支付
          </b>
        </p>,
        "",
        [
          {
            text: "取消",
            onPress: (value) =>
              new Promise((resolve) => {
                resolve();
              }),
          },
          {
            text: "支付",
            onPress: (value) =>
              new Promise((resolve, reject) => {
                if (value * 1 + "" === "NaN") {
                  return Toast.fail("只能输入数字噢!", 1);
                }
                if (value !== "") {
                  global.Ajax.hhtc_request("dynamic/user_live").then((data) => {
                    console.log("data: ", data);

                    if (data.code === 1) {
                      Toast.success(data.msg, 1);
                      window.location.reload();
                      console.log("time: ", time);
                      resolve();
                    } else {
                      Toast.fail(data.msg, 1);
                    }
                  });
                } else {
                  Toast.fail("请输入打赏数量");
                }
              }),
          },
        ],
        "default",
        5,
        ["请输入要打赏的小红花数量"]
      );
    } else {
      // 获取现在时间秒数  home/live_time

      var time = Math.round(new Date());

      if (time > this.state.live_time) {
        global.Ajax.hhtc_request("home/live_time").then((data) => {
          console.log("data: ", data);
        });
      }
    }
  }

  render() {
    return (
      <div className='' style={{ paddingBottom: 70 }}>
        <div className='home_search_box'>
          <img
            alt=''
            src={require("../../imgs/msg.png")}
            className='msg'
            onClick={() => {
              this.props.history.push("/page/home/home/msg");
            }}
          />
          <div
            onClick={() => {
              this.props.history.push("/page/home/home/search");
            }}
          >
            <img
              alt=''
              src={require("../../imgs/search.png")}
              className='search_icon'
            />
            <span>搜索内容</span>
          </div>
          {/* <img alt='' src={require('../../imgs/head.png')} className='defa' /> */}
        </div>
        <Carousel
          autoplay={false}
          infinite
          className='index_banner'
          dotStyle={{
            width: 4,
            height: 4,
            borderRadius: "100%",
            background: "rgba(255,255,255,.75)",
            marginBottom: 6,
          }}
          dotActiveStyle={{
            width: 10,
            height: 4,
            borderRadius: 4,
            background: "#fff",
            marginBottom: 6,
          }}
        >
          {/* 这里之前是0   onClick={this.xh.bind(this)}     */}
          {this.state.live_status !== 0
            ? this.state.banner.map((item, index) => {
                return (
                  <img
                    key={"banner" + index}
                    alt=''
                    src={item.img}
                    onClick={this.xh.bind(this)}
                    className='banner_img'
                  />
                );
              })
            : this.state.banner.map((item, index) => {
                return (
                  <a href={item.url}>
                    <img
                      key={"banner" + index}
                      alt=''
                      src={item.img}
                      className='banner_img'
                    />
                  </a>
                );
              })}
        </Carousel>
        <Grid
          className='index_menu index_menu1'
          data={this.state.category}
          columnNum={5}
          hasLine={false}
          activeStyle={false}
          renderItem={(Item) => (
            <div
              className='item'
              onClick={() => {
                // if(Item.path!=''){
                this.props.history.push("/page/home/home/classify/" + Item.id);
                // }
              }}
            >
              <img alt='' src={Item.icon} />
              <p>{Item.title}</p>
            </div>
          )}
        />

        <Grid
          className='index_menu'
          data={this.state.menu}
          columnNum={5}
          hasLine={false}
          activeStyle={false}
          renderItem={(Item) => (
            <div
              className='item'
              onClick={() => {
                if (Item.name == "艺看直播") {
                  window.location.href = Item.path;
                } else {
                  this.props.history.push(Item.path);
                }
              }}
            >
              <img alt='' src={Item.icon} />
              <p>{Item.name}</p>
            </div>
          )}
        />
        {this.state.img.img != undefined && (
          <img
            alt=''
            src={this.state.img.img}
            className='yinl_img'
            onClick={() => {
              // this.props.history.push('/page/home/user/drainage')
              window.location.href = this.state.img.url;
            }}
          />
        )}
        <div className='title_box'>
          <h1>主编力荐</h1>
          <p
            onClick={() => {
              if (this.state.category.length > 1) {
                this.props.history.push(
                  "/page/home/home/classify/" + this.state.category[0].id
                );
              }
            }}
          >
            <span>更多</span>
            <img alt='' src={require("../../imgs/r2.png")} />
          </p>
        </div>
        <div className='index_lj_list'>
          {this.state.hot_goods.map((item, index) => {
            return (
              <div
                className='item'
                key={"lj" + index}
                onClick={() => {
                  this.props.history.push(
                    "/page/home/learn/learndetail/" + item.id
                  );
                }}
              >
                <div className='picbox'>
                  <img alt='' src={item.img} className='pic' />
                  <p className='bq1'>{item.type === 1 ? "视频" : "听书"}</p>
                </div>
                <div className='right'>
                  <p className='title'>{item.title}</p>
                  <p className='desc'>{item.info}</p>
                  <p className='peop'>{item.author}</p>
                  <div className='flex'>
                    <p className='pri'>{(item.z_price * 1000) / 1000}</p>
                    {item.is_jiang === 1 && <p className='bq'>分享有奖</p>}
                    <p className='play_btn'>
                      <img
                        alt=''
                        src={require("../../imgs/sanj.png")}
                        className='sanj'
                      />
                      <span>{item.is_st == 1 ? "试学" : "购买"}</span>
                    </p>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
        {/* <div className='title_box'>
          <h1>交流活动</h1>
          <p
            onClick={() => {
              this.props.history.push("/page/home/home/activity/抖音培训/1");
            }}
          >
            <span>更多</span>
            <img alt='' src={require("../../imgs/r2.png")} />
          </p>
        </div> */}
        {/* <div className='activity_list'>
          {this.state.active.map((item, index) => {
            return (
              <div
                className='item'
                key={"act" + index}
                onClick={() => {
                  this.props.history.push(
                    "/page/home/signup/detail/" + item.id
                  );
                }}
              >
                <img alt='' src={item.img} className='pic' />
                <div className='right'>
                  <p className='title'>{item.title}</p>
                  <p className='addr'>{item.address}</p>
                  <p className='time'>{item.time}</p>
                </div>
              </div>
            );
          })}
        </div> */}
        {/* <div className='title_box'>
          <h1>招生活动</h1>
          <p
            onClick={() => {
              this.props.history.push("/page/home/home/activity/活动报名/2");
            }}
          >
            <span>更多</span>
            <img alt='' src={require("../../imgs/r2.png")} />
          </p>
        </div> */}
        {/* <div className='sign_index_list'>
          {this.state.hot_active.map((item, index) => {
            return (
              <div
                className='item'
                style={{
                  marginBottom: "10px",
                  borderBottom: "1px solid #ccc",
                  paddingBottom: "10px",
                }}
                key={"sign" + index}
                onClick={() => {
                  this.props.history.push(
                    "/page/home/signup/detail/" + item.id
                  );
                }}
              >
                <img alt='' src={item.img} className='pic' />
                <p className='title'>{item.title}</p>
                <p className='desc'>{item.info}</p>
                <p className='peop'>{item.name}</p>
              </div>
            );
          })}
        </div> */}
        {/* <div className='huod_img_list'>
          {this.state.server_casee.map((item, index) => {
            return (
              <img
                onClick={() => {
                  return Toast.info("开发中，敬请期待");
                  this.props.history.push(
                    "/page/home/home/service/" + item.title + "/" + item.id
                  );
                }}
                key={"img" + index}
                alt=''
                src={item.img}
                className='img'
              />
            );
          })}
        </div> */}
        {this.state.data.map((item, index) => {
          return (
            item.data.length > 0 && (
              <React.Fragment key={"data" + index}>
                <div className='title_box'>
                  <h1>{item.title}</h1>
                  <p
                    onClick={() => {
                      this.props.history.push(
                        "/page/home/home/classify/" + item.id
                      );
                    }}
                  >
                    <span>更多</span>
                    <img alt='' src={require("../../imgs/r2.png")} />
                  </p>
                </div>
                <div className='sy_list'>
                  {item.data.map((child, k) => {
                    return (
                      <div
                        className='item'
                        key={"child" + k}
                        onClick={() => {
                          this.props.history.push(
                            "/page/home/learn/learndetail/" + child.id
                          );
                        }}
                      >
                        <div className='picbox'>
                          <img alt='' src={child.img} className='pic' />
                          <p className='bq'>
                            {child.type === 1 ? "视频" : "听书"}
                          </p>
                        </div>
                        <p className='title'>{child.title}</p>
                      </div>
                    );
                  })}
                </div>
              </React.Fragment>
            )
          );
        })}
      </div>
    );
  }
}
